/* model */
import {
  ProductLineRoleMap, 
  SelectUserComponentRole 
} from "@src/component/common/BaseSelectUser/model";
import { getProductLineRoleName, SHBProductLineEnum, validateNeedExtraHandleRoleList } from "@shb-lib/tenant";
/* util */
import {
  roleListGroupByProductLineToMap
} from "@shb-lib/tenant";
import { isRoleSelectType } from "@src/component/common/BaseSelectUser/util/selected";
/* types */
import { BaseSelectUserSelectedItemType } from "@src/component/common/BaseSelectUser/types";
import { isFalsy } from "@src/util/type";

type TransformRoleListOptionsType = {
  // 是否只显示 服务云 角色
  isOnlyShowBusinessServiceCloudRole?: boolean;
}

/** 
 * @description 转换角色列表数据，适应不同产品线
*/
function transformRoleList(roleList: SelectUserComponentRole[], options?: TransformRoleListOptionsType): SelectUserComponentRole[] {
  
  const { 
    isNotNeedExtraHandleRole, 
    productLineMap, 
    _isHaveBusinessServiceCloudProductLine 
  } = validateNeedExtraHandleRoleList(roleList)
  
  // 如果没有 客服云 或 服务云 产品线，则返回原始数据，不做处理
  if (isNotNeedExtraHandleRole) {
    return roleList;
  }
  
  // 是否配置了只显示 服务云 角色
  const isOnlyShowBusinessServiceCloudRole = Boolean(options?.isOnlyShowBusinessServiceCloudRole);
  
  /** 
   * 如果有服务云版本角色 且 配置了只显示 服务云 角色，
   * 则返回 服务云 角色列表 和 待分配 角色列表
  */
  if (_isHaveBusinessServiceCloudProductLine && isOnlyShowBusinessServiceCloudRole) {
    return [
      ...productLineMap[SHBProductLineEnum.BusinessServiceCloud],
      ...productLineMap[SHBProductLineEnum.UnAllot]
    ]
  }
  
  const productLineRoleKeys = Object.keys(ProductLineRoleMap)
  const newRoleList: SelectUserComponentRole[] = [];
  
  productLineRoleKeys.forEach((productLineRoleKey) => {
    
    // 当前产品线对应的角色列表数据
    const currentProductLineRoleList = productLineMap[productLineRoleKey as SHBProductLineEnum]
    // 是否有当前产品线对应的角色列表数据
    const isHaveProductLine = Boolean(currentProductLineRoleList);
    
    if (isHaveProductLine) {
      
      const newRole: SelectUserComponentRole = {
        ...ProductLineRoleMap[productLineRoleKey],
        // 汇总当前产品线下的用户数量
        userCount: currentProductLineRoleList.reduce((previousValue, currentValue) => {
          previousValue += currentValue.userCount
          return previousValue
        }, 0),
        tagChildren: currentProductLineRoleList
      }
      
      newRoleList.push(newRole);
      
    }
    
  });
  
  return newRoleList;
}

function transformRoleName(data: BaseSelectUserSelectedItemType) {
  
  // 暂时不添加角色前缀了，直接返回原始数据
  return data;
  
  // const isRoleType = isRoleSelectType(data)
  
  // if (isFalsy(isRoleType)) {
  //   return data;
  // }
  
  // const roleName = getProductLineRoleName<SelectUserComponentRole>(data as SelectUserComponentRole)
  
  // return {
  //   ...data,
  //   name: roleName
  // }
  
}

export {
  roleListGroupByProductLineToMap,
  transformRoleName,
  transformRoleList
}